<?php
/**
 * Created by PhpStorm.
 * User: Dean.Wu
 * Date: 2018/2/24 0024
 * Time: 15:18
 */
namespace App\Http\Controllers\Admin;

use App\Models\AdminRole;
use App\Models\AdminUsers;
use App\User;

class UsersController extends Controller{

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @name 后台用户列表
     * @author Dean.wu
     */
    public function index(){
        $lists=AdminUsers::orderBy('id','desc')->paginate(15);
        return view('admin.users.index',compact("lists"));
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @name 创建页面
     * @author Dean.wu
     */
    public function create(){
        return view('admin.users.create');
    }

    /**
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * @name 存储信息
     * @author
     */
    public function store(){
        $this->validate(request(), [
            'name' => 'required|min:3',
            'password' => 'required'
        ]);
        $name = request('name');
        $password = bcrypt(request('password'));
        AdminUsers::create(compact('name', 'password'));
        return redirect('/admin/users');
    }

    /**
     * @param AdminUsers $user
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @name 角色权限
     */
    public function role(AdminUsers $user){
        $roles = AdminRole::all();
        $myRoles = $user->roles;
        return view('admin.users.role', compact('roles', 'myRoles', 'user'));
    }

    /**
     * @param AdminUsers $user
     * @return \Illuminate\Http\RedirectResponse
     * @name 保存权限
     */
    public function storeRole(AdminUsers $user)
    {
        $this->validate(request(),[
            'roles' => 'required|array'
        ]);

        $roles = AdminRole::find(request('roles'));
        $myRoles = $user->roles;
        if(!$myRoles){
            $myRoles=[];
        }
        // 对已经有的权限
        $addRoles = $roles->diff([]);

        foreach ($addRoles as $role) {
            $user->roles()->save($role);
        }

        $deleteRoles = $myRoles->diff($roles);
        foreach ($deleteRoles as $role) {
            $user->deleteRole($role);
        }
        return back();
    }
}